package be.pluyckx.batteryprogress.activity.fragment.info;

import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import java.text.DecimalFormat;

import be.pluyckx.batteryprogress.R;
import be.pluyckx.batteryprogress.application.Constants;
import be.pluyckx.batteryprogress.components.adapter.ProcessListAdapter;
import be.pluyckx.batteryprogress.components.view.DescriptionView;
import be.pluyckx.batteryprogress.components.view.TitleBoxLayout;
import be.pluyckx.batteryprogress.data.history.BatteryHistory;
import be.pluyckx.batteryprogress.data.history.BatteryLevel;
import be.pluyckx.batteryprogress.data.history.snapshot.ProcessSnapshot;
import be.pluyckx.batteryprogress.utils.calculator.BatteryHistoryWrapper;
import be.pluyckx.batteryprogress.utils.calculator.ProgressCalculator;
import be.pluyckx.batteryprogress.utils.calculator.RealTimeProgressCalculator;

/**
 * Created by Philip on 19/08/13.
 *
 * A Fragment for more details about an item in the BatteryHistory. This can be used in a Dialog.
 */
public class ItemDetailsFragment extends DialogFragment {
  private static final String TAG = "ItemDetailsFragment";

  private static final String STATE_INDEX = "stat_index";

  private static final ProgressCalculator mCalculator = new RealTimeProgressCalculator();
  private static final ProgressCalculator.Parameters mParameters = new ProgressCalculator.Parameters(ProgressCalculator.Parameters.ORDERED_OLD_LOWEST_INDEX);
  private static final DecimalFormat mFormat = new DecimalFormat("0.0%/h");
  private DescriptionView mDvLevel;
  private DescriptionView mDvDate;
  private DescriptionView mDvSpeed;
  private DescriptionView mDvActiveActivity;
  private TitleBoxLayout mRunningProcesses;
  private ListView mProcessList;
  private int mIndex = -1;
  private boolean mCreated = false;

  /**
   * Create a new ItemDetailsFragment. This is the same as calling {@code ItemDetailsFragment(-1)}.
   */
  public ItemDetailsFragment() {
    this(-1);
  }

  /**
   * Create a new ItemDetailsFragment with an @{code itemIndex}. This index is used as index
   * for the BatteryHistory object.
   *
   * @param itemIndex
   */
  public ItemDetailsFragment(int itemIndex) {
    mIndex = itemIndex;
  }

  @Override
  public void onStart() {
    super.onStart();

    if (mIndex == -1) {
      dismiss();
    }
  }

  @Override
  public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

    if (Constants.DEBUG) {
      Log.i(TAG, "onSaveInstanceState");
    }

    outState.putInt(STATE_INDEX, mIndex);
  }

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    if (savedInstanceState != null) {
      if (mIndex == -1) {
        mIndex = savedInstanceState.getInt(STATE_INDEX, -1);
      }
    }

    if (mIndex != -1) {
      View v = inflater.inflate(R.layout.fragment_item_details, container, false);

      mDvLevel = (DescriptionView) v.findViewById(R.id.dv_level);
      mDvDate = (DescriptionView) v.findViewById(R.id.dv_date);
      mDvSpeed = (DescriptionView) v.findViewById(R.id.dv_speed);
      mDvActiveActivity = (DescriptionView) v.findViewById(R.id.descriptionview_active_activity);
      mProcessList = (ListView) v.findViewById(R.id.listview_running_processes);
      mProcessList.setAdapter(new ProcessListAdapter(getActivity(),
              BatteryHistory.getHistory().get(mIndex).getProcessesSnapshot()));
      mRunningProcesses = (TitleBoxLayout) v.findViewById(R.id.titlebox_running_processes);

      BatteryLevel level = BatteryHistory.getHistory().get(mIndex);
      ProcessSnapshot snapshot = level.getProcessesSnapshot();
      mRunningProcesses.setTitle(getResources().getString(R.string.group_running_processes) +
          " (" + (snapshot != null ? snapshot.count() : getResources().getString(R.string.unknown)) + ")");

      getDialog().setTitle(R.string.dialog_detailed_info);
      mCreated = true;

      updateView();

      return v;
    } else {
      return null;
    }
  }

  /**
   * Update the Views in this fragment with the correct information.
   */
  private void updateView() {
    if (!mCreated) {
      return;
    }

    if (mIndex != -1) {
      BatteryLevel level = BatteryHistory.getHistory().get(mIndex);
      ProcessSnapshot snapshot = level.getProcessesSnapshot();
      mDvLevel.setDescription(level.getBatteryLevelPercentageAsString());
      mDvDate.setDescription(level.getDateString());

      if (snapshot != null && snapshot.getCurrentActivity() != null) {
        mDvActiveActivity.setDescription(level.getProcessesSnapshot().getCurrentActivity());
      } else {
        mDvActiveActivity.setDescription(getResources().getString(R.string.no_active_activity));
      }

      ProgressCalculator.Result result = mCalculator.calculate(new BatteryHistoryWrapper(BatteryHistory.getHistory()), mParameters, mIndex);

      if (result != null && result.getNewestItem() != result.getOldestItem()) {
        mDvSpeed.setDescription(mFormat.format(result.getPercentPerHour()));
      } else {
        mDvSpeed.setDescription(getResources().getString(R.string.unknown));
      }
    }
  }
}
